package org.xxpay.apibase.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionMethod;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xxpay.apibase.constant.ABCS;
import org.xxpay.apibase.util.DateKit;
import org.xxpay.apibase.util.ZIPKit;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

public class ApiCtrlKit {

    private static final Logger logger = LoggerFactory.getLogger(ApiCtrlKit.class);

    /** 生成zip文件， 并存放到dist目录下 **/
    public static JSONObject genZip(HttpServletRequest request, Class clazz) {

        JSONObject result = new JSONObject();

        try {

            String classFilePath = request.getParameter("classFilePath");
            String ifTypeCode = request.getParameter("ifTypeCode");
            String ifTypeName = request.getParameter("ifTypeName");
            String param = request.getParameter("param");
            String supportConfigType = request.getParameter("supportConfigType");
            String payInterfaceArray = request.getParameter("payInterfaceArray");


            if(!new File(classFilePath + File.separator + ifTypeCode).isDirectory()){
                result.put("errMsg", "[" + ifTypeCode + "] 文件夹不存在！ 请检查是否正确编译！");
                return result;
            }
            if(new File(classFilePath + File.separator + ifTypeCode).listFiles().length <= 0){
                result.put("errMsg", "[" + ifTypeCode + "] 文件夹内 .class文件不存在！ 请检查是否正确编译！");
                return result;
            }

            //临时文件夹
            String tempDir = System.getProperty("java.io.tmpdir")+"dctmp"+System.nanoTime();
            new File(tempDir).mkdirs();

            //1. 生成 [jar] 文件
            ZipFile appJarFile = new ZipFile(tempDir + File.separator +"app.jar");
            for (File file : new File(classFilePath + File.separator + ifTypeCode).listFiles()) {
                ZipParameters zipParameters = new ZipParameters();
                zipParameters.setCompressionMethod(CompressionMethod.DEFLATE);
                zipParameters.setFileNameInZip("org/xxpay/dc/" + ifTypeCode + "/" + file.getName());
                ByteArrayInputStream bs = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));
                appJarFile.addStream(bs, zipParameters);
                bs.close();
            }

            //2. 生成 [app.json] 文件
            JSONObject appJSON = new JSONObject();
            appJSON.put("ifTypeCode", ifTypeCode);
            appJSON.put("ifTypeName", ifTypeName);
            appJSON.put("param", JSONArray.parseArray(param));
            appJSON.put("supportConfigType", supportConfigType);
            appJSON.put("payInterfaceArray", JSONArray.parseArray(payInterfaceArray));

            //写入 app.json
            FileUtils.writeStringToFile(
                    new File(tempDir + File.separator + "app.json" ), appJSON.toJSONString(), "UTF-8");

            //写入 if.check文件
            ZIPKit.genIfCheckFile(tempDir, ABCS.IFSTORE_IFCHECK_PWD);

            String realFileName = new File(clazz.getResource("").getFile())
                    .getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getAbsolutePath()
                    + File.separator + "src"
                    + File.separator + "main"
                    + File.separator + "java"
                    + File.separator + "org"
                    + File.separator + "xxpay"
                    + File.separator + "dist"
                    + File.separator + ifTypeCode
                    + File.separator + "xxpay-dc-"+ifTypeCode+"_"+ DateKit.date2Str(DateKit.FORMAT_APPEND) +".zip";

            new File(realFileName).getParentFile().mkdirs(); //创建文件， 避免报错

            ZipFile realZipFile = new ZipFile(realFileName);
            ZipParameters zipParameters = new ZipParameters();
            zipParameters.setCompressionMethod(CompressionMethod.DEFLATE);
            for (File file : new File(tempDir).listFiles()) {
                realZipFile.addFile(file, zipParameters);
            }

            //删除目录
            FileUtils.deleteDirectory(new File(tempDir));
            result.put("realFileName", realFileName);

        } catch (IOException e) {
            logger.error("error:", e);
            result.put("errMsg", e.getMessage());
        }

        return result;
    }

}
